package com.movisol.messengercommunicator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;

import com.movisol.messengercommunicator.data.CommunicatorRoot;
import com.movisol.messengercommunicator.events.DataLoadedEvent;
import com.movisol.messengercommunicator.helper.MessengerCommunicatorHelper;
import com.movisol.messengercommunicator.ilisteners.IConversationsListLoaded;
import com.movisol.messengercommunicator.ilisteners.IMessagePosted;
import com.movisol.messengercommunicator.ilisteners.IMessagesListLoaded;
import com.movisol.tools.HelperUtils;

public class CommunicatorManager {
	
	Context context = null;
	protected List<IConversationsListLoaded> conversationListLoadedListeners = new ArrayList<IConversationsListLoaded>();
	protected List<IMessagesListLoaded> messagesListLoadedListeners = new ArrayList<IMessagesListLoaded>();
	protected List<IMessagePosted> messagePostedListeners = new ArrayList<IMessagePosted>();
	
	public CommunicatorManager(Context context)
	{
		this.context = context;
	}
	
	
	/******************ConversationListLoaded*****************/
	public synchronized void addConversationListLoadedListener(IConversationsListLoaded listener){
		if(!conversationListLoadedListeners.contains(listener))
			conversationListLoadedListeners.add(listener);
	}
	
	
	public synchronized void removeConversationListLoadedListener(IConversationsListLoaded listener){
		
		conversationListLoadedListeners.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void fireConversationsListLoaded(String error){
		
		DataLoadedEvent dle = null;
		dle = new DataLoadedEvent(this, error);
		Iterator<IConversationsListLoaded> it = conversationListLoadedListeners.listIterator();
		while (it.hasNext()){
			 it.next().conversationListLoaded(dle);
		}
	}
	/********************************************************/
	
	
	
	/******************MessagesListLoaded*****************/
	public synchronized void addMessagesListLoadedListener(IMessagesListLoaded listener){
		if(!messagesListLoadedListeners.contains(listener))
			messagesListLoadedListeners.add(listener);
	}
	
	
	public synchronized void removeMessagesListLoadedListener(IMessagesListLoaded listener){
		
		messagesListLoadedListeners.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void fireMessagesListLoaded(String error){
		
		DataLoadedEvent dle = null;
		dle = new DataLoadedEvent(this, error);
		Iterator<IMessagesListLoaded> it = messagesListLoadedListeners.listIterator();
		while (it.hasNext()){
			 it.next().messagesListLoaded(dle);
		}
	}
	/********************************************************/
	
	
	
	/******************MessagePosted*****************/
	public synchronized void addMessagePostedListener(IMessagePosted listener){
		if(!messagePostedListeners.contains(listener))
			messagePostedListeners.add(listener);
	}
	
	
	public synchronized void removeMessagePostedListener(IMessagePosted listener){
		
		messagePostedListeners.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void fireMessagePosted(String error){
		
		DataLoadedEvent dle = null;
		dle = new DataLoadedEvent(this, error);
		Iterator<IMessagePosted> it = messagePostedListeners.listIterator();
		while (it.hasNext()){
			 it.next().messagePosted(dle);
		}
	}
	/********************************************************/
	

	//GET method
	public String getConversationList(String userId, String signature)
	{
		URL url;
		String result = null;
		BufferedReader br = null;
		try {
			url = new URL(HelperUtils.getConfigParam("FQDNC", context)+ "/Service.svc/Conversations/"+ userId + "/" + signature + "/");
			URLConnection c =  url.openConnection();
			c.setDoOutput(true);
			c.connect();
			InputStreamReader ins = new InputStreamReader(c.getInputStream());

			
			br = new BufferedReader(ins, 8192);
			StringBuffer sb = new StringBuffer();

			//Guardamos el stream recibido			
			String len1;
			while ((len1 = br.readLine()) != null) {
				sb.append(len1);
			}
			result = sb.toString();

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (ProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
	            if (br != null) {
	                try {
	                	br.close();
	                } catch (IOException ex) {
	                    System.out.println("Problema al cerrar el objeto lector");
	                }
	            }
		}

		return result;
	}
	
	public String getXMLfromUri(String conversationsListUri)
	{
		BufferedReader reader = null;
		URI uri = null;
		String result = null;
		HttpClient client = null;
		HttpResponse response = null;

		try {

			client = new DefaultHttpClient();
			uri = new URI(conversationsListUri);
			HttpGet request = new HttpGet(uri);
			
		    response = client.execute(request);
		    
		    InputStream in;
		    in = response.getEntity().getContent();
		    reader = new BufferedReader(new InputStreamReader(in), 8192);
			
			StringBuffer sb = new StringBuffer();

			//Guardamos el stream recibido			
			String len1;
			String NL = System.getProperty("line.separator");
			while ((len1 = reader.readLine()) != null) {
				sb.append(len1+NL);
			}
			result = sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (URISyntaxException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally
		{
			if (reader != null) {
                try {
                	reader.close();
                	reader = null;
                } catch (IOException ex) {
                    System.out.println("Problema al cerrar el objeto lector");
                }
            }
		}

		return result;
		
	}
	
	//GET method
	public String getMessageList(String conversationId)
	{
		URL url;
		String result = null;
		BufferedReader br = null;
		try {
			url = new URL(HelperUtils.getConfigParam("FQDNC", context)+ "/Service.svc/Conversation/"+ conversationId + "/");
			URLConnection c =  url.openConnection();
			c.setDoOutput(true);
			c.connect();
			InputStreamReader ins = new InputStreamReader(c.getInputStream());

			
			br = new BufferedReader(ins, 8192);
			StringBuffer sb = new StringBuffer();

			//Guardamos el stream recibido			
			String len1;
			while ((len1 = br.readLine()) != null) {
				sb.append(len1);
			}
			result = sb.toString();

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (ProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
	            if (br != null) {
	                try {
	                	br.close();
	                } catch (IOException ex) {
	                    System.out.println("Problema al cerrar el objeto lector");
	                }
	            }
		}

		return result;
	}
	
	public String postMessage(CommunicatorRoot message, String userId)
	{
		URL url;
		String result = null;
		BufferedReader br = null;
		

	    try {
	    	url = new URL(HelperUtils.getConfigParam("FQDNC", context)+ "/Service.svc/Messages/"+ userId + "/");
			 // Create a new HttpClient and Post Header
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(url.toString());
		    String sXML = MessengerCommunicatorHelper.parseCommunicatorRootToXML(message);
	    	StringEntity se = new StringEntity(sXML,"UTF-8");
	    	se.setContentType("text/xml"); 
	        httppost.setEntity(se);

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        
	        br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8192);
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
				while ((line = br.readLine()) != null) {
					sb.append(line + NL);
				}
				br.close();
			result = sb.toString();
	    } catch (ClientProtocolException e) {

	    } catch (UnsupportedEncodingException e) {

	    } catch (IOException e) {

	    } catch (IllegalArgumentException e) {

	    }

	    
		
		return result;
	}
	

}
